<template>
  <ContentWrap :style="`height: ${contentHeight}px;`">
    <div class="mb-10px routeHeader">
      <template v-if="['update'].includes(formType)">
        <el-button
          @click="submitForm('save')"
          type="primary"
          :disabled="formLoading"
          v-hasPermi="['report:order-cost-finance:save']"
          >保存</el-button
        >
        <el-button
          @click="submitForm('handle')"
          type="primary"
          :disabled="formLoading"
          v-hasPermi="['report:order-cost-finance:handle']"
          >提交</el-button
        >
      </template>
      <el-button @click="goBack">关闭</el-button>
    </div>
    <el-scrollbar :max-height="`${contentHeight - 73}px`">
      <el-table 
        v-loading="formLoading" 
        :data="list" 
        row-key="id"
        ref="multipleTableRef"
      >
        <el-table-column label="序号" align="center" type="index" width="60" fixed="left" />
        <el-table-column 
          v-for="item, index in detailTableTitleList"
          :key="index"
          :label="item.label" 
          :headerAlign="item.headerAlign"
          :align="item.align" 
          :min-width="item.width"
          :prop="item.field"
        >
          <template #default="scope" >
            <!-- 二级表头 -->
            <template v-if="item.children">
              <el-table-column 
                v-for="child, childIndex in item.children"
                :key="childIndex"
                :label="child.label" 
                :align="child.align" 
                :headerAlign="child.headerAlign"
                :prop="child.field"
                :min-width="child.width"
              >
                <template #default="scope">
                  <!-- 字典翻译 -->
                  <dict-tag v-if="child['dictType']" :type="child['dictType']" :value="scope.row[child.field]" />
                  <template v-else>
                    <!-- 时间戳处理 -->
                    <div v-if="child['isTime']">{{ formatDate(scope.row[child.field]) }}</div>
                    <template v-else>
                      <!-- 输入框 -->
                      <div v-if="child['isInput']">
                        <template v-if="child['isNumber']" >
                          <!-- 占比 -->
                          <el-input-number 
                            v-if="child.field === 'financeProportion'"
                            v-model="scope.row[child.field]" 
                            :precision="2" 
                            controls-position="right"
                            :disabled="formType === 'view'"
                            :min="0"
                            :max="100"
                          />
                          <el-input-number 
                            v-else
                            v-model="scope.row[child.field]" 
                            :precision="4" 
                            controls-position="right"
                            @change="setTotal(scope.$index)"
                            />
                        </template>
                        <!-- 字符串输入框 -->
                        <el-input v-else v-model="scope.row[child.field]" :disabled="formType === 'view'" />
                      </div>
                      <div v-else>{{ scope.row[child.field] }}</div>
                    </template>
                  </template>
                </template>
              </el-table-column>
            </template>
            <!-- 一级表头 -->
            <template v-else>
              <!-- 字典翻译 -->
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <template v-else>
                <!-- 时间戳处理 -->
                <div v-if="item.isTime">{{ formatDate(scope.row[item.field]) }}</div>
                <template v-else>
                  <!-- 字符串输入框 -->
                  <el-input v-if="item.isInput" v-model="scope.row[item.field]" :disabled="formType === 'view'" />
                  <div v-else>{{ scope.row[item.field] }}</div>
                </template>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </ContentWrap>
</template>
<script setup lang="ts">
import * as OrderCostFinanceApi from '@/api/reportQuery/orderReport/orderCostFinance'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { detailTableTitleList } from './tableTitle-data'
import { formatDate } from '@/utils/formatTime'

const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：view - 查看；update - 修改
const contentHeight = ref(0)
const list = ref<OrderCostFinanceApi.OrderCostFinanceVO[]>([])

const query = useRoute().query as any

/** 获取数据 */
const getData = async () => {
  formType.value = query.type
  const id = query.id.split(',')
  formLoading.value = true
  try {
    list.value = await OrderCostFinanceApi.getOrderCostFinance({ ids: id })
  } finally {
    formLoading.value = false
  }
}

// 关闭
const tagsViewStore = useTagsViewStore()
const { currentRoute, push } = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(currentRoute.value)
  push('/reportQuery/reportQuery/orderReport/orderCostFinance')
}

// 计算合计
const setTotal = (index: number) => {
  list.value[index].financeTotalPrice = 
    // 主材
    (list.value[index].financePrincipalMaterial || 0) +
    // 辅材
    (list.value[index].financeAuxiliaryMaterial || 0) +
    // 外协
    (list.value[index].financeOutsourcing || 0) +
    // 运费
    (list.value[index].financeFreight || 0) +
    // 电气
    (list.value[index].financeElectric || 0)
}

/** 提交表单 */
const submitForm = async (type: string) => {
  // 提交请求
  formLoading.value = true
  try {
    const data = list.value as unknown as OrderCostFinanceApi.OrderCostFinanceVO[]
    // submitFlag 1 保存 2 提交
    data.map(item => {
      item.submitFlag = type === 'save' ? 1 : 2
      return item
    })
    await OrderCostFinanceApi.updateOrderCostFinance({ createList: data })
    message.success('操作成功')
    goBack()
  } finally {
    formLoading.value = false
  }
}

onMounted(() => {
  contentHeight.value = document.body.clientHeight - 125
  getData()
})
</script>
